<?php

namespace frontend\controllers;

use bc\controller\SampleController;
use bc\controller\WxOAuthController;
use bc\model\wc\AgentspreadModel;
use bc\model\wc\SpreadModel;
use bc\model\wc\StaffModel;
use bc\wx\pay\WxPayException;
use bc\wx\pay\WxPayJsApiPay;
use bc\wx\pay\WxPayApi;
use bc\wx\pay\WxPayUnifiedOrder;
use yii\web\Cookie;
use yii\web\Session;
use bc\model\wc\BookingModel;
use bc\model\wc\BpointModel;
use bc\wx\User as User;
use bc\model\UserModel as zUser;
use bc\model\OrderModel;
use bc\service\SpokesmanService;
use bc\model\order\DetailModel;
use bc\model\product\DistributionModel;
use bc\model\product\detail\BounsModel;
use bc\model\product\QrcodeModel;
use bc\util\Math;

class WxpayController extends SampleController
{
	const BODY = '平台服务费';
	
	/**
	 */
	public function actionIndex()
	{
		$session = new Session ();
		$user = $session->get ( 'shop_user' );
		$wx_user = $session->get('user');
		
		$id = $this->get ( 'id' );
		
		$bookingId = $this->get('booking_id', 0);
		
		$orderModel = new OrderModel();
		$orderModel->autoId = 'order_id';
		$order = $orderModel->getRowOne(['user_id' => $user['user_id'], 'order_id' => $id, 'order_status' => 1, 'pay_status' => 0]);

		if(!$order)
			$this->redirect('/');
			
		$orderNo = $order['order_no'];
		$totalFee = $order['pay_amount'] * 100;
		
		
		$WxPayUnifiedOrder = new WxPayUnifiedOrder ();
		$WxPayUnifiedOrder->SetAppid ( $this->wechat ()->appid );
		$WxPayUnifiedOrder->SetMch_id ( $this->wechat ()->mchid );
		$WxPayUnifiedOrder->SetBody ( self::BODY );
		$WxPayUnifiedOrder->SetOut_trade_no ( 'zsmm' . $orderNo );
		$WxPayUnifiedOrder->SetTotal_fee ( $totalFee );
		$WxPayUnifiedOrder->SetSpbill_create_ip ( $_SERVER ['REMOTE_ADDR'] );
		$WxPayUnifiedOrder->SetNotify_url ( $this->getRequest ()->hostInfo . '/wxnotify/notify' );
		$WxPayUnifiedOrder->SetTrade_type ( 'JSAPI' );
		$WxPayUnifiedOrder->SetOpenid ( $wx_user ['openid'] );
		
		$wxOrder = WxPayApi::unifiedOrder ( $WxPayUnifiedOrder );
		
		$jsApiParameters = $this->GetJsApiParameters ( $wxOrder );
		
		
		$view ['id'] = $id;
		$view ['booking_id'] = $bookingId;
		
		$view ['jsApiParameters'] = $jsApiParameters;
		return $this->render ( 'index', $view );
	}
	
	
	/**
	 * Ajax订单状态变更
	 */
	public function actionChangestatus()
	{
		if ($this->getRequest ()->isAjax)
		{
			$session = new Session ();
			$user = $session->get ( 'shop_user' );
			
			$id = $this->post ( 'id' );
			$bookingId = $this->post('booking_id', 0);
			
			
			$orderModel = new OrderModel();
			$orderModel->autoId = 'order_id';
			$order = $orderModel->getRowOne(['user_id' => $user['user_id'], 'order_id' => $id]);
			if($order)
			{
				//支付完成更新订单状态
				$orderModel->modify(['order_status' => 2, 'pay_status' => 1, 'pay_time' => time()], $order['order_id']);
				
				//更新无创预约单的
				if ($bookingId)
				{
					$bookingModel = new BookingModel ();
					$whereUserModel = array (
							'id' => $bookingId
					);
					$bookingModelRow = $bookingModel->getRow ( $whereUserModel );
					if ($bookingModelRow)
					{
						if ($bookingModelRow ['status'] == 1) // 订单未支付
						{
							$bookingModel->modify ( [
									'status' => 2,
									'order_payment_time' => time ()
							], $bookingId );
						}
					}
				}
			}
			
			try 
			{
				$orderModel->columns = [DetailModel::getTableSchema()->name . '.product_id', OrderModel::getTableSchema()->name . '.user_id', DetailModel::getTableSchema()->name . '.order_detail_id'];
				$orderInfo = $orderModel->getInfoByFrontend(['bc_order.order_id' => $id]);
					
				$spokesmanService = new SpokesmanService();
				foreach ($orderInfo as $orderItem)
				{
					$distributionModel = new DistributionModel();
					$distribution = $distributionModel->getRow(['product_id' => $orderItem['product_id']]);
					if($distribution)//分利商品
					{
						
						//通过分享二维码首次购买商品
						$spokesmanService = new SpokesmanService();
						$recommendProductArr = $session->get('recommend_product');
						$recommendProduct = $recommendProductArr[$orderItem['product_id']];
						if($recommendProduct)
						{
							unset($recommendProductArr[$product_id]);
							//清空session数据
							$session->set('recommend_product', $recommendProductArr);
						}
						//end
						
						
						//生成等级关系
						$return = $spokesmanService->createLevel($orderItem['product_id'], $orderItem['user_id'], $recommendProduct['parent_user_id']?$recommendProduct['parent_user_id']:0);
						
						
						$qrcodeModel = new QrcodeModel();
						$qrcode = $qrcodeModel->getRow(['user_id' => $orderItem['user_id'], 'product_id' => $orderItem['product_id'], 'is_delete' => 0 ]);
						
						
						if(!$qrcode)
						{
							//创建用户专属二维码
							$spokesmanService->createProductQrcode($orderItem['product_id'], $user);
						}
						
// 						if($return == true)
// 						{
// 							//创建用户专属二维码
// 							$spokesmanService->createProductQrcode($orderItem['product_id'], $user);
// 						}
						
						//获取所有父级
						$muliData = $spokesmanService->getParent($orderItem['user_id'], $orderItem['product_id']);
						if(!empty($muliData))
						{
							$bounsModel = new BounsModel();
							$bounsModel->createBouns($muliData, $orderItem['product_id'], $orderItem['order_detail_id']);
						}
						
					}
				
				}
			}
			catch (\Exception $e)
			{
				file_put_contents('/tmp/log/error.log', $e->getMessage() . "\n", FILE_APPEND);
			}
			
		}
	}
	
	/**
	 * 支付成功页
	 */
	public function actionSuccess()
	{
		$session = new Session ();
		$reqCookies = $this->getRequest()->cookies;
		$user = $session->get ( 'user' );
		$wx_user = $session->get('shop_user');
		
		$id = $this->get ( 'id' );
		$bookingId = $this->get('booking_id', 0);
		
		if (! $id)
			$this->redirect ( '/' );
			
		$orderModel = new OrderModel();
// 		$order = $orderModel->getRowById($id);
			
		$orderModel->columns='bc_product.product_id,bc_order.order_id,bc_product.category_id';
		$orderInfo = $orderModel->getInfoByFrontend(['bc_order.order_id' => intval($id)]);
		
         
		//微信js分享
		$jsConfig = $this->configJsApi();
		
		//判断用户是否有推广码
		$productQrcodeModel = new QrcodeModel();
		$productQrcode = $productQrcodeModel->getRow(['product_id' => $orderInfo[0]['product_id'], 'user_id' => $wx_user['user_id'], 'is_delete' => 0]);
		if($productQrcode)
		{
			$view['product_recommend_image'] =  $productQrcode['image'];
		}
		
		$view['order'] = $orderInfo;
		if($bookingId)	
		{
			// 页面数据信息
			$bookingModel = new BookingModel ();
			$whereUserModel = array (
					'id' => $id
			);
			$bookingModelRow = $bookingModel->getRow ( $whereUserModel );
			
			$userModel = new zUser ();
			$whereUserModel = array (
					'id' => $bookingModelRow ['user_id']
			);
			$userModelRow = $userModel->getRow ( $whereUserModel );
			$bookingModelRow ['name'] = $userModelRow ['real_name'];
			$bookingModelRow ['idcard'] = $userModelRow ['idcard'];
			$bookingModelRow ['idcard_type'] = $userModel->getIdCardType ( $userModelRow ['idcard_type'] );
			$bookingModelRow ['birthday'] = $userModelRow ['birthday'];
			$bookingModelRow ['mobile_phone'] = $userModelRow ['mobile'];
			
			// 获取采血点和事务
			$bpointModel = new BpointModel ();
			$bpointData = $bpointModel->getRowById ( $bookingModelRow ['bpoint_id'] );
			
			$staffModel = new StaffModel ();
			$staffData = $staffModel->getStaffFromBid ( [
					'hospital_id' => $bookingModelRow ['bpoint_id']
			] );
			// $doctorModel= new DoctorModel();
			// $doctorModel->columns='bc_wc_doctor.id as d_id,user_id,hospital_id,phone,bc_wc_hospital.id as h_id,name,address,bc_user.id as uid,real_name,nick_name,wxid';
			// $doctorData=$doctorModel->getDoctorList(array('bc_wc_doctor.id'=>$bookingModelRow['doctor_id']));
			
			$view ['bpointData'] = $bpointData;
			$view ['staffData'] = $staffData;
			// $view ['doctorData'] = $doctorData;
			
			$view ['row'] = $bookingModelRow;
			// 订单支付完成修改推广记录
			$spreadModel = new SpreadModel ();
			$status = 2;
			if(!$spreadModel->setSpreadStatus ( $wx_user ['openid'], $status ) or $reqCookies->get('recommend_wc') )
			{
				$user_id=$reqCookies->get('recommend_wc');
				$AgentspreadM = new AgentspreadModel();
				$data['recommend_user_id']=$user_id;
				$data['order_id']=$id;
				$data['spread_status']=2;
				$data['create_time']=time();
				$AgentspreadM->add($data);
			}
			
			
			//判断购买用户的推荐人类型
			$spreadRow = $spreadModel->getRow(['user_penid' => $wx_user['openid']]);
			$view ['spread'] = $spreadRow;
			
		}
		
		//肥胖分享
		
		if($orderInfo[0]['product_id'] == 2)
		{
			$view ['jsapi']['js_config']     = $jsConfig;
			$view ['jsapi']['share_url']     = $this->getRequest()->hostInfo.'/product/detail?id='.$orderInfo[0]['product_id'];
			$view ['jsapi']['share_title']   = '滚蛋吧，肥胖君';
			$view ['jsapi']['share_content'] = '找到DNA中的减肥机密';
			$qrcodeModel = new QrcodeModel();
			$qrcode = $qrcodeModel->getRow(['product_id' => $orderInfo[0]['product_id'], 'user_id' => $user_id, 'is_delete' => 0]);
			if($qrcode)
			{
				$view ['jsapi']['share_url'] .= '&c=' . $qrcode['code'];
			}
			
			
		}
		
		//计算一级代理享受的金额
		$distributionModel = new DistributionModel();
		$distribution = $distributionModel->getRow(['product_id' => $orderInfo[0]['product_id']]);
		if($distribution)
		{
			$discount_price =  Math::ConverToCeil($distribution['distribution_price'] * $distribution['level_1'], 1);
			$view['discount_price'] = $discount_price;
		}
		
		
		if($bookingId)
		{
			return $this->render('booking_success', $view);
		}
		elseif($orderInfo[0]['category_id'] == 1) 
		{
			$this->getHtmlFromPid($orderInfo[0]['product_id']);
			$view ['product_html']=$this->html;
			return $this->render ( 'gene_success', $view );
        }else{
                        
			$this->getHtmlFromPid($orderInfo[0]['product_id']);
			$view ['product_html']=$this->html;
			return $this->render ( 'normal_success', $view );
		}
		
	}
	
	/**
	 *
	 * 获取jsapi支付的参数
	 *
	 * @param array $UnifiedOrderResult
	 *        	统一支付接口返回的数据
	 * @throws WxPayException
	 *
	 * @return json数据，可直接填入js函数作为参数
	 */
	public function GetJsApiParameters($UnifiedOrderResult)
	{
		if (! array_key_exists ( "appid", $UnifiedOrderResult ) || ! array_key_exists ( "prepay_id", $UnifiedOrderResult ) || $UnifiedOrderResult ['prepay_id'] == "")
		{
			throw new WxPayException ( "参数错误" );
		}
		$jsapi = new WxPayJsApiPay ();
		$jsapi->SetAppid ( $UnifiedOrderResult ["appid"] );
		$timeStamp = time ();
		$jsapi->SetTimeStamp ( "$timeStamp" );
		$jsapi->SetNonceStr ( WxPayApi::getNonceStr () );
		$jsapi->SetPackage ( "prepay_id=" . $UnifiedOrderResult ['prepay_id'] );
		$jsapi->SetSignType ( "MD5" );
		$jsapi->SetPaySign ( $jsapi->MakeSign () );
		$parameters = json_encode ( $jsapi->GetValues () );
		return $parameters;
	}
	
	/*
	 * 页面数据保存
	 */
	public function actionSavedate()
	{
		$session = new Session ();
		$user = $session->get ( 'user' );
		$userDate ['real_name'] = $this->post ( 'name', '' );
		$userDate ['birthday'] = $this->post ( 'birthday', '' );
		$userDate ['mobile'] = $this->post ( 'mobile', '' );
		$userDate ['idcard'] = $this->post ( 'idcard', '' );
		$userDate ['idcard_type'] = $this->post ( 'idcard_type', '' );
		$userDate ['update_time'] = date ( 'Y-m-d H:i:s', time () );
		$userDate ['is_invalid'] = 1;
		// 更新bc_user表
		$userModel = new zUser ();
		$whereUserModel = array (
				'wxid' => $user ['openid'] 
		);
		$userModelRow = $userModel->getRow ( $whereUserModel );
		$userModel->modify ( $userDate, $userModelRow ['id'] );
		
		$data ['childbirth_date'] = $this->post ( 'duedate' );
		$data ['bpoint_id'] = $this->post ( 'collection' );
		// $data['doctor_id'] = $this->post('doctor');
		$data ['user_id'] = $userModelRow ['id'];
		$data ['update_time'] = time ();
		$data ['is_invalid'] = 1;
		$data ['status'] = 1;
		$data ['report_url'] = "";
		
		$bookingModel = new BookingModel ();
		$whereUserModel = array (
				'user_id' => $userModelRow ['id'] 
		);
		$bookingModelRow = $bookingModel->getRow ( $whereUserModel );
		if (empty ( $bookingModelRow ))
		{
			
			// 查看用户是那个医生推广的。
			$whereSpreadModel = array (
					'user_penid' => $user ['openid'] 
			);
			$spreadM = new SpreadModel ();
			$bookingModelRow = $spreadM->getRow ( $whereSpreadModel );
			$data ['doctor_id'] = $bookingModelRow ['duser_id'];
			
			$data ['create_time'] = time ();
			$data ['order_no'] = date ( 'YmdHis' ) . rand ( 10000000, 99999999 );
			$returnid = $bookingModel->add ( $data );
			
			// 生产订单的同事修改推广记录
			$spreadModel = new SpreadModel ();
			$status = 1;
			$spreadModel->setSpreadStatus ( $user ['openid'], $status );
		}
		else
		{
			$returnid = $bookingModelRow ['id'];
			$bookingModel->modify ( $data, $bookingModelRow ['id'] );
		}
		if ($returnid)
		{
			echo json_encode ( $returnid );
		}
	}
}
        
        